<template>
  <div v-if="breadcrumbMap" class="page-header">
    <el-breadcrumb>
      <el-breadcrumb-item v-for="(m, key) in breadcrumbMap" :key="key">
        <template v-if="m.notClickable">
          {{ m.name }}
        </template>
        <router-link v-else :to="key">{{ m.name }}</router-link>
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>
<script>
import { mapState } from 'vuex';
const getBreadcrumbMap = (menuData, route) => {
  const { path } = route;
  if (path === '/') {
    return null;
  }
  const result = {};
  const childResult = {};
  const matched = ['/location', route.path];
  for (const menu of menuData) {
    if (matched.includes(menu.path)) {
      menu.notClickable = true;
    }
    if (route.path.indexOf(menu.path) !== -1) {
      result[menu.path] = menu;
    }
    if (menu.children) {
      Object.assign(childResult, getBreadcrumbMap(menu.children, route));
    }
  }
  return Object.assign({}, result, childResult);
};

export default {
  data() {
    return {
      breadcrumbMap: null,
    };
  },
  computed: {
    ...mapState(['menuData']),
  },
  watch: {
    $route: function() {
      this.buildBreadcrumb();
    },
    menuData: function() {
      this.buildBreadcrumb();
    },
  },
  created() {
    this.buildBreadcrumb();
  },
  methods: {
    buildBreadcrumb() {
      const route = this.$route;
      const menuData = this.menuData;
      this.breadcrumbMap = getBreadcrumbMap(menuData, route);
    },
  },
};
</script>

<style lang="less" scoped>
.page {
  &-header {
    background: #fff;
    padding: 16px 32px 0;
    border-bottom: 1px solid #e8e8e8;
    .el-breadcrumb {
      margin-bottom: 16px;
    }
  }
}
</style>
<style lang="less">
.page-header {
  .el {
    &-breadcrumb {
      &__item {
        &:last-child {
          .el-breadcrumb__inner.is-link {
            color: rgba(0, 0, 0, 0.65);
          }
        }
      }
      &__inner {
        color: rgba(0, 0, 0, 0.45);
        &.is-link,
        a {
          color: rgba(0, 0, 0, 0.45);
          font-weight: normal;
          &:hover {
            color: #40a9ff;
          }
        }
      }
      &__separator {
        margin: 0 8px;
        color: rgba(0, 0, 0, 0.45);
        font-weight: normal;
      }
    }
  }
}
</style>
